﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Storage;

namespace BackgroundAgant
{
    public sealed class BackgroundHelper
    {
        private const string CnBlogsBackgroundTaskName = "cnBlogsBackgroundTask";
        private const string CnBlogsBackgroundTasktaskEntryPoint = "BackgroundAgant.cnBlogsBackgroundTask";
        private static bool IstaskRegistered = false;

        public static IBackgroundTaskRegistration checkRegistration()
        {
            foreach (var task in BackgroundTaskRegistration.AllTasks)
            {
                if (task.Value.Name == CnBlogsBackgroundTaskName)
                {
                    IstaskRegistered = true;
                    return task.Value;
                }
            }
            return null;
        }
        public static IBackgroundTaskRegistration RegisteBackgroundTask(IBackgroundTrigger trigger, IBackgroundCondition condition, string taskEntryPoint, string name)
        {
            IBackgroundTaskRegistration result = checkRegistration();
            if (result != null)
                return result;
            var builder = new BackgroundTaskBuilder();
            builder.Name = name ?? CnBlogsBackgroundTaskName;
            builder.TaskEntryPoint = taskEntryPoint ?? CnBlogsBackgroundTasktaskEntryPoint;
            builder.SetTrigger(trigger);
            if (condition != null)
            {
                builder.AddCondition(condition);
            }
            result = builder.Register();
            return result;
        }

        public static void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
        {
            var settings = ApplicationData.Current.LocalSettings;
            var key = task.TaskId.ToString();
            //var message = settings.Values[key].ToString();

        }
    }
}
